using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Reflection;
using System.Web.UI;
using System.IO;
using System.Configuration.Provider;

namespace Barbar.MapReport.HtmlRender.Handlers {
  internal class FileHandler : ProviderBase, ISimpleHttpHandler {
    private static SortedList<string, WebResourceAttribute> Attributes;
    private static object SyncRoot = new object();

    private static SortedList<string, WebResourceAttribute> AttributeCache {
      get {
        lock (SyncRoot) {
          if (Attributes == null) {
            Attributes = new SortedList<string, WebResourceAttribute>();
            Assembly assembly = Assembly.GetExecutingAssembly();
            WebResourceAttribute[] attributes = (WebResourceAttribute[])assembly.GetCustomAttributes(typeof(WebResourceAttribute), false);
            foreach (WebResourceAttribute attribute in attributes)
              Attributes.Add(attribute.WebResource, attribute);
          }
        }
        return Attributes;
      }
    }

    #region ISimpleHttpHandler Members

    public void ProcessRequest(HttpContext context) {
      string file = context.Request["file"];
      if (AttributeCache.ContainsKey(file)) {
        HttpResponse response = context.Response;

        response.Cache.SetCacheability(HttpCacheability.Public);
        response.Cache.VaryByParams.IgnoreParams = false;
        response.Cache.SetMaxAge(TimeSpan.FromDays(1));

        WebResourceAttribute resource = AttributeCache[file];
        response.ContentType = resource.ContentType;
        Assembly assembly = Assembly.GetExecutingAssembly();
        using (Stream stream = assembly.GetManifestResourceStream(file)) {
          byte[] buffer = new byte[stream.Length];
          stream.Read(buffer, 0, buffer.Length);
          response.OutputStream.Write(buffer, 0, buffer.Length);
          stream.Close();
        }
      } else
        throw new FileNotFoundException(file);
    }

    #endregion
  }
}
